<template>
  <div>
    <div class="container">
      <div class="handle-box">
        <el-button type="primary" size="mini" @click="delAll">批量删除</el-button>
        <el-input class="handle-input" v-model="search_text" placeholder="请输入关键字" size="mini" prefix-icon="el-icon-search" clearable />
        <el-button type="primary" size="mini" @click="addDialogVisiable = true">添加用户</el-button>
      </div>

      <el-table size="mini" @selection-change="handleSelectionChange" border style="width:100%" height="668px" :data="data">
        <el-table-column type="selection" width="40"></el-table-column>
        <el-table-column label="用户图片" width="110" align="center">
          <template slot-scope="scope">
            <div class="consumer-img">
              <img :src="getUrl(scope.row.avatar)" style="width: 58px;">
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户" width="200" align="center"></el-table-column>
        <el-table-column label="性别" width="100" align="center">
          <template slot-scope="scope">
            {{changeSex(scope.row.sex)}}
          </template>
        </el-table-column>
        <el-table-column prop="email" label="电子邮箱" width="300" align="center"></el-table-column>
        <el-table-column label="生日" width="200" align="center">
          <template slot-scope="scope">
            {{attachDate(scope.row.birth)}}
          </template>
        </el-table-column>
        <el-table-column prop="introduction" label="签名" width="550" align="center"></el-table-column>
        
        <el-table-column label="操作" width="250" align="center">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

    <div class="pagination">
      <el-pagination background class="page"
      layout="total,prev,pager,next"
      :current-page="currentPage"
      :page-size="pageSize"
      :total="tableData.length"
      @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
    <el-dialog title="添加新用户" :visible.sync="addDialogVisiable" center width="400px">
      <el-form :model="registerForm" id="registerForm" ref="registerForm" :rules="rules" label-width="80px" :inline="false" size="small">
        <el-form-item prop="username" label="用户名" size="mini">
          <el-input name="username" v-model="registerForm.username" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码" size="mini">
          <el-input name="password" type="password" v-model="registerForm.password" placeholder="密码">
            <template v-if="registerForm.password" slot="append">{{passwordlevel}}</template>
          </el-input>
        </el-form-item>
        <el-form-item prop="checkPass" label="确认">
          <el-input type="password" v-model="registerForm.checkPass" placeholder="确认密码"></el-input>
        </el-form-item>
        <el-form-item prop="sex" label="性别">
          <el-radio-group v-model="registerForm.sex">
            <el-radio name="sex" :label="0">女</el-radio>
            <el-radio name="sex" :label="1">男</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="email" label="邮箱" size="mini">
          <el-input name="email" v-model="registerForm.email" placeholder="邮箱"></el-input>
        </el-form-item>
        <el-form-item prop="birth" label="生日" size="mini">
          <el-date-picker name="birth" v-model="registerForm.birth" placeholder="选择日期" size="mini" style="width:100%"></el-date-picker>
        </el-form-item>
        <el-form-item prop="introduction" label="签名" size="mini">
          <el-input name="introduction" type="textarea" maxlength="200" v-model="registerForm.introduction" placeholder="签名"></el-input>
        </el-form-item>
        <el-form-item prop="pic" label="头像" size="mini">
          <input type="file" name="file" id="video_pic">
        </el-form-item>
      </el-form>
      <span></span>
      <span slot="footer">
        <el-button type="primary" @click="addConsumer">确定</el-button>
        <el-button @click="addDialogVisiable = false">取消</el-button>
      </span>
    </el-dialog>

    <el-dialog title="修改用户" :visible.sync="editVisiable" center width="400px">
      <el-form :model="form" id="form" ref="form" :rules="rules" label-width="80px" :inline="false" size="small">
        <el-form-item prop="username" label="用户名" size="mini">
          <el-input name="username" v-model="form.username" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item prop="password2" label="密码" size="mini">
          <el-input name="password" type="password" v-model="form.password2" placeholder="密码">
            <template v-if="form.password2" slot="append">{{editpasswordlevel}}</template>
          </el-input>
        </el-form-item>
        <el-form-item prop="sex" label="性别">
          <el-radio-group v-model="form.sex">
            <el-radio name="sex" :label="0">女</el-radio>
            <el-radio name="sex" :label="1">男</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="email" label="邮箱" size="mini">
          <el-input name="email" v-model="form.email" placeholder="邮箱"></el-input>
        </el-form-item>
        <el-form-item prop="birth" label="生日" size="mini">
          <el-date-picker name="birth" v-model="form.birth" placeholder="选择日期" size="mini" style="width:100%"></el-date-picker>
        </el-form-item>
        <el-form-item prop="introduction" label="签名" size="mini">
          <el-input name="introduction" type="textarea" maxlength="200" v-model="form.introduction" placeholder="签名"></el-input>
        </el-form-item>
        <el-form-item prop="pic" label="头像" size="mini">
          <input type="file" name="file" id="video_pic">
        </el-form-item>
      </el-form>
      <span></span>
      <span slot="footer">
        <el-button type="primary" @click="editConsumer">确定</el-button>
        <el-button @click="editVisiable = false">取消</el-button>
      </span>
    </el-dialog>

    <el-dialog title="删除用户" :visible.sync="delVisible" center width="300px">
      <div align="center">删除不可恢复，是否确定删除？</div>
      <span slot="footer">
        <el-button type="primary" @click="deleteRow">确定</el-button>
        <el-button @click="delVisible = false">取消</el-button>
      </span>
    </el-dialog>
    
    </div>
  </div>
</template>

<script>
import {getAllConsumer, setConsumer,delConsumer, updateConsumer} from '../api/index'
import {mixin} from '../mixins/index'
export default {
  mixins:[mixin],
  data(){
    //检查密码
    var validatePassword = (rule,value,callback) =>{
      if(value === ''){
        callback(new Error('请输入密码'))
      }else if(value.length<6){
        callback(new Error('密码不得少于6位'))
      }else{
        if(this.registerForm.checkPass !== ''){
          this.$refs.registerForm.validateField('checkPass')
        }
      }
      callback()
    }
    var editvalidatePassword = (rule,value,callback) =>{
      if(value === ''){
        callback(new Error('请输入密码'))
      }else if(value.length<6){
        callback(new Error('密码不得少于6位'))
      }
      callback()
    }
    var validatePassword2 = (rule,value,callback) =>{
      if(value === ''){
        callback(new Error('请再次输入密码'))
      }else if(value !== this.registerForm.password){
        callback(new Error('两次输入密码不一致'))
      }else{
        callback()
      }
    }
    return {
      idx:-1,     //记录当前选中的行
      multipleSelection:[],  //那些项已经打钩
      search_text:'',  //筛选的关键字
      addDialogVisiable:false,  //添加用户框
      delVisible:false,
      editVisiable:false,
      tableData:[],   //显示的用户信息
      tempData:[],    //暂存的用户信息
      currentPage:1,  //当前页
      pageSize:8,    //每一页个数
      registerForm:{  //添加新用户表
        username:'',
        password:'',
        sex:'',
        email:'',
        birth:'',
        introduction:'',
      },
      form:{  //修改用户表
        id:'',
        username:'',
        password:'',
        sex:'',
        email:'',
        birth:'',
        introduction:'',
      },
      rules:{
        username:[
          {required:true,trigger:'blur',message:'请输入用户名'}
        ],
        password:[
          {required:true,validator:validatePassword,trigger:'blur'}
        ],
        password2:[
          {required:true,validator:editvalidatePassword,trigger:'blur'}
        ],
        checkPass:[
          {required:true,validator:validatePassword2,trigger:'blur'}
        ],
        sex:[
          {required:true,message:'请选择性别'}
        ],
        birth:[
          {required:true,message:'请选择日期',trigger:'change'}
        ],
        email:[
          {required:true,message:'请输入电子邮箱',trigger:'blur'},
          {type:'email',message:'请输入正确的电子邮箱地址',trigger:['blur','change']}
        ],
        introduction:[
          {required:false,message:'请输入签名',trigger:'blur'},
        ],
      },
    }
  },
  watch:{
    search_text:function(){
      this.currentPage = 1
      if(this.search_text == ''){
        this.tableData = this.tempData
      }else{
        this.tableData = []
        for(let item of this.tempData){
          if(item.username.includes(this.search_text)){
            this.tableData.push(item)
          }
        }
      }
    }
  },
  computed:{
    data(){
      return this.tableData.slice((this.currentPage-1)*this.pageSize,this.currentPage*this.pageSize)
    },
    //计算密码强度
    passwordlevel(){
      let level;
      if(/\d/.test(this.registerForm.password) && /[a-z]/.test(this.registerForm.password) && /[A-Z]/.test(this.registerForm.password)){
        level = '强'
      }else if(/^\d+$/.test(this.registerForm.password) || /^[A-Z]+$/.test(this.registerForm.password) || /^[a-z]+$/.test(this.registerForm.password)){
        level = '弱'
      }else{
        level = '中'
      }
      return level
    },
    editpasswordlevel(){
      let level;
      if(/\d/.test(this.form.password) && /[a-z]/.test(this.form.password) && /[A-Z]/.test(this.form.password)){
        level = '强'
      }else if(/^\d+$/.test(this.form.password) || /^[A-Z]+$/.test(this.form.password) || /^[a-z]+$/.test(this.form.password)){
        level = '弱'
      }else{
        level = '中'
      }
      return level
    }
  },
  created(){
    this.getData();
  },
  methods:{
    //获取当前页
    handleCurrentChange(val){
      this.currentPage = val;
    },
    //查询所有用户
    getData(){
      this.tempData=[]
      this.tableData=[]
      getAllConsumer()
        .then(res =>{
          this.tempData = res
          this.tableData = res
          this.currentPage = 1
        }).catch(err =>{
          console.log(err);
        })
    },
    
    //编辑用户信息
    handleEdit(row){
      this.form = {
        id:row.id,
        username:row.username,
        password2:row.password,
        sex:row.sex,
        email:row.email,
        birth:row.birth,
        introduction:row.introduction,
      }
      this.editVisiable = true;
    },
    editConsumer(){
      this.$refs['form'].validate(valid =>{
        if(valid){
          var formData = new FormData(document.getElementById("form"));
          formData.append('id',this.form.id)
          updateConsumer(formData)
          .then(res =>{
            if(res.code == 1){
              this.getData();
              this.notify("修改成功","success")
            }else{
              this.notify("修改失败","error")
            }
          }).catch(err => {
            console.log(err)
          })
          this.editVisible = false;
        }
      })
    },
    
    //删除用户
    deleteRow(){
      delConsumer(this.idx)
        .then(res =>{
          if (res) {
            this.getData();
            this.notify('删除成功','success')
          }else{
            this.notify('删除失败','error')
          }
        })
    this.delVisible = false
    },
    //点击确定后添加用户
    addConsumer(){
      this.$refs['registerForm'].validate(valid =>{
        if(valid){
          var formData = new FormData(document.getElementById("registerForm"));
          setConsumer(formData)
          .then(res =>{
            if(res.code == 1){
              this.getData();
              this.notify("添加成功","success")
            }else{
              this.notify("添加失败","error")
            }
          }).catch(err => {
            console.log(err)
          })
          this.addDialogVisible = false;
        }
      })
    }
  }
}
</script>

<style scoped>
@import '../assets/css/consumer.css';
</style>